﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Fis.Win.Utils;
using Agile.Engine.Utils;
using System.Text.RegularExpressions;
using DevExpress.XtraEditors;

namespace Fis.Win.Forms
{
    public partial class AccountTreatForm : BaseForm
    {
        public AccountTreatForm()
        {
            InitializeComponent();
        }

        #region //共通

        private void AccountTreatForm_Load(object sender, EventArgs e)
        {
            InitializeForm();
        }

        private void TxtLog_TextChanged(object sender, EventArgs e)
        {
            TxtLog.SelectionStart = TxtLog.Text.Length;
            TxtLog.ScrollToCaret();
        }

        private void BtnOK_Click(object sender, EventArgs e)
        {
            switch (Text)
            {
                case "结束初始化":
                    InitializeBillCheck();
                    break;
                case "反初始化":
                    ReverseInitializeSubmit();
                    break;
                case "结转损益":
                    TransferProfit();
                    break;
                case "期末调汇":
                    AdjustRate();
                    break;
                case "凭证审核":
                    if (RadBtn1.Checked == true)
                    {
                        CertificateAudit();
                    }
                    else
                    {
                        ReverseCertificateAudit();
                    }
                    break;
                case "凭证过账":
                    CertificatePosting();
                    break;
                case "凭证反过账":
                    ReverseCertificatePosting();
                    break;
                case "结账":
                    AccountSettle();
                    break;
                case "反结账":
                    ReverseAccountSettle();
                    break;
                default:
                    break;
            }

            Close();
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void BtnRate_Click(object sender, EventArgs e)
        {
            if (Fis.Win.Utils.AppSession.RightsValidata("BD.Rate", "View"))
                UIManager.ShowList<Forms.RateListForm>("RateListViewProvider");
        }

        private void InitializeForm()
        {
            Text = ViewModel["FormName"].ToString();
            switch (Text)
            {
                case "结束初始化"://结束初始化
                    TxtLog.Text = "------------------------------------------------------\r\n";
                    TxtLog.Text += "";
                    TxtLog.Text += "------------------------------------------------------\r\n";
                    Panel1.Visible = true;
                    RadBtn1.Text = "结束初始化";
                    break;
                case "反初始化"://反初始化
                    TxtLog.Text = "------------------------------------------------------\r\n";
                    TxtLog.Text += "";
                    TxtLog.Text += "------------------------------------------------------\r\n";
                    Panel1.Visible = true;
                    RadBtn1.Text = "反初始化";
                    break;
                case "结转损益"://结转损益
                    TxtLog.Text = "说明：\r\n";
                    TxtLog.Text += "    损益类科目的余额将全部结转到“本年利润”中，结转后，损益科目余额为零。";
                    TxtLog.Text += "注意：\r\n";
                    TxtLog.Text += "    结转损益只针对本期已过账凭证,如结转完成后修改或增加过损益类科目需再次结转损益。\r\n";
                    Panel2.Visible = true;
                    Fis.Win.Utils.UIUtils.LookUpBinding(CBoxAccount1, Fis.Win.Utils.CacheContext.GetCache("TACCOUNT"), "FDETAILNAME", "SID");
                    break;
                case "期末调汇"://结转损益
                    TxtLog.Text = "------------------------------------------------------\r\n";
                    TxtLog.Text += "";
                    TxtLog.Text += "------------------------------------------------------\r\n";
                    Panel3.Visible = true;
                    Fis.Win.Utils.UIUtils.LookUpBinding(CBoxAccount2, Fis.Win.Utils.CacheContext.GetCache("TACCOUNT"), "FDETAILNAME", "SID");
                    break;
                case "凭证审核"://审核
                    TxtLog.Text = "说明：\r\n";
                    TxtLog.Text += "    审核是为了保证凭证和账簿的准确有效性，对凭证的内容，金额，相关要素的完备性等进行审查，避免出现凭证的错误。\r\n";
                    TxtLog.Text += "    反审核是将已经审核完的记账凭证进行取消审核操作，反审核只针对本人进行审核的凭证。\r\n\r\n";
                    TxtLog.Text += "注意：\r\n";
                    TxtLog.Text += "    审核前，请仔细核对凭证的内容，金额，相关要素的完备性，防止将错误的凭证予以审核。\r\n";
                    TxtLog.Text += "    反审核前，请核对已经审核完的记账凭证是否无误，如无需要，请不要进行此操作，反审核过的凭证需要再次进行审核。\r\n";
                    Panel1.Visible = true;
                    RadBtn1.Text = "审核";
                    RadBtn2.Text = "反审核";
                    RadBtn2.Enabled = true;
                    RadBtn2.Visible = true;
                    break;
                case "凭证过账"://过账
                    TxtLog.Text = "说明：\r\n";
                    TxtLog.Text += "    过账是将本期生成的所有凭证中的业务，逐笔登记到总分类账户和明细分类账户中，进行一些基本的汇总，便于今后的查询和报表的输出。\r\n\r\n";
                    TxtLog.Text += "注意：\r\n";
                    TxtLog.Text += "    过账前，请确保凭证完全准确无误，凭证一旦过账，就不能进行修改，如果发现错误，请点击取消按钮，采用补充凭证或者红字冲销的方法进行更正。\r\n";
                    Panel1.Visible = true;
                    RadBtn1.Text = "过账";
                    break;
                case "凭证反过账"://反过账
                    TxtLog.Text = "说明：\r\n";
                    TxtLog.Text += "    反过账是将已经记完的账目恢复到过账前的状态。\r\n\r\n";
                    TxtLog.Text += "注意：\r\n";
                    TxtLog.Text += "    反过账前，请核对已经过账完的记账凭证是否无误，如无需要，请不要进行此操作，反过账过的凭证需要再次进行过账。\r\n";
                    Panel1.Visible = true;
                    RadBtn1.Text = "反过账";
                    break;
                case "结账"://结账
                    TxtLog.Text = "说明：\r\n";
                    TxtLog.Text += "    结账是将一定时期内应记入账簿的经济业务全部登记入账后，计算记录本期发生额和期末余额，并将余额结转下期或新的账簿。\r\n\r\n";
                    TxtLog.Text += "注意：\r\n";
                    TxtLog.Text += "    结账前，应先检查本期发生的各种经济业务是否都已经编制记账凭证并登记入账。对各种成本费用类账户，也应当在结账前对余额进行结转，并登记入账。\r\n";
                    Panel1.Visible = true;
                    RadBtn1.Text = "结账";
                    break;
                case "反结账"://反结账
                    TxtLog.Text = "说明：\r\n";
                    TxtLog.Text += "    反结账是将已经结完的账恢复到结账前的状态。\r\n\r\n";
                    TxtLog.Text += "注意：\r\n";
                    TxtLog.Text += "    反结账过程中请做好数据备份，务必确保数据的准确性，防止数据的丢失或损坏。\r\n";
                    Panel1.Visible = true;
                    RadBtn1.Text = "反结账";
                    break;
                default:
                    break;
            }
        }

        #endregion

        #region //初始化

        private void InitializeBillCheck()
        {
            if (Fis.Win.Utils.AppSession.IsComplateInitialize)
            {
                XtraMessageBox.Show("已结束初始化");
                return;
            }
            System.Collections.Hashtable mode = new System.Collections.Hashtable();
            ViewModel["Action"] = "初始凭证检测";
            mode = ViewProvider.ExecuteQuery(ViewModel);
            if (mode["State"].Equals(0))
            {
                if (XtraMessageBox.Show(string.Format("初始凭证数：{0},是否继续结束初始化？", mode["BillMasterCount"]), "", MessageBoxButtons.YesNo) ==
                        System.Windows.Forms.DialogResult.Yes)
                {
                    InitializeRestBuild();
                }
            }
            else if (mode["State"].Equals(-1))//凭证未上传
            {
                XtraMessageBox.Show("请先提交初始化数据");
                System.Collections.Hashtable model = new System.Collections.Hashtable();
                model["filter0"] = " AND FSTATUS=4";
                model["filter1"] = string.Empty;
                model["listtype"] = "init";

                UIManager.ShowList<Forms.BillListForm>("BillListViewProvider", model);
            }
            else
            {
                XtraMessageBox.Show(string.Format("错误初始凭证数：{0},请修改后，重新结束初始化！", mode["ErrorBillMasterCount"]));
                string ErrorBillID = mode["ErrorBillMasterID"].ToString();
                System.Collections.Hashtable model = new System.Collections.Hashtable();
                model["filter0"] = string.Format("and m.SID in ('{0}') ", ErrorBillID);
                model["filter1"] = "";
                model["listtype"] = "init";
                UIManager.ShowList<Forms.BillListForm>("BillListViewProvider", model);
            }
            return;
        }

        private void InitializeRestBuild()
        {
            System.Collections.Hashtable mode = new System.Collections.Hashtable();
            ViewModel["Action"] = "初始科目余额表生成";
            mode = ViewProvider.ExecuteQuery(ViewModel);
            var m = (string)null;
            if (mode["State"].Equals(0))
            {
                m = "科目余额生成成功。\r\n";
                m += mode["Log"].ToString();
                m += "确认科目余额，是否继续结束初始化？（是/否）。";
                if (XtraMessageBox.Show(m, "", MessageBoxButtons.YesNo) ==
                       System.Windows.Forms.DialogResult.Yes)
                {
                    InitializeSubmit(mode);
                }
            }
            else
            {
                m = "科目余额生成失败。\r\n";
                m += mode["Log"].ToString();
                m += "科目余额借贷不平，请调整后重新结束初始化！";
                XtraMessageBox.Show(m);
            }
            return;
        }

        private void InitializeSubmit(System.Collections.Hashtable mode)
        {
            mode["Action"] = "初始化提交";
            if (ViewProvider.ExecuteUpdate(mode))
            {
                XtraMessageBox.Show("结束初始化成功！");
            }
            else
            {
                XtraMessageBox.Show("结束初始化失败,请稍候重试！");
            }
            return;
        }

        private void ReverseInitializeSubmit()
        {
            if (!Fis.Win.Utils.AppSession.IsComplateInitialize)
            {
                XtraMessageBox.Show("当前已经是未结束初始化状态");
                return;
            }
            if (int.Parse(ViewModel["Range"].ToString()) > int.Parse(ViewModel["InitializeRange"].ToString()))
            {
                XtraMessageBox.Show("请先反结账到账套启用期间！");
                return;
            }
            if (XtraMessageBox.Show("结束初始化将清空科目余额表！是否继续？", "", MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes)
            {
                return;
            }
            ViewModel["Action"] = "反初始化提交";
            if (ViewProvider.ExecuteUpdate(ViewModel))
            {
                XtraMessageBox.Show("反初始化成功！");
                //ViewProvider.InitializeViewModel(ViewModel);
                Close();
            }
            else
            {
                XtraMessageBox.Show("反初始化失败,请稍候重试！");
            }
            return;
        }

        #endregion

        #region //结转损益

        private void TransferProfit()
        {
            System.Collections.Hashtable mode = new System.Collections.Hashtable();
            ViewModel["Action"] = "结转损益";
            ViewModel["FEXPLANATION"] = TxtRemark.Text;
            ViewModel["FACCOUNTCODE"] = (CBoxAccount1.EditValue == null) ? "default_3131" : CBoxAccount1.EditValue;
            mode = ViewProvider.ExecuteQuery(ViewModel);
            if (mode["State"].Equals(-1))
            {
                ShowUnSyncForm();
                return;
            }
            XtraMessageBox.Show(mode["Message"].ToString());
            if (mode["State"].Equals(0))
            {
                Close();
            }
            return;
        }

        #endregion

        #region //期末调汇

        private void AdjustRate()
        {
            System.Collections.Hashtable mode = new System.Collections.Hashtable();
            ViewModel["Action"] = "期末调汇";
            //ViewModel["FEXPLANATION"] = TxtRemark.Text;
            ViewModel["FACCOUNTCODE"] = (CBoxAccount2.EditValue == null) ? "default_5503" : CBoxAccount2.EditValue;
            mode = ViewProvider.ExecuteQuery(ViewModel);
            if (mode["State"].Equals(-1))
            {
                ShowUnSyncForm();
                return;
            }
            XtraMessageBox.Show(mode["Message"].ToString());
            if (mode["State"].Equals(0))
            {
                Close();
            }
            return;
        }

        #endregion

        #region //凭证审核

        private void CertificateAudit()
        {
            var BillMasterTB = ViewModel["BillMasterTB"] as DataTable;
            if (int.Parse(BillMasterTB.Compute("count(SID)", string.Format("FSTATUS=0 and (FENTER<>'{0}' or FENTER is null)", ViewModel["FCHECKED"])).ToString()) == 0)
            {
                XtraMessageBox.Show("没有其他人录入的凭证需要审核！");
                return;
            }
            System.Collections.Hashtable mode = new System.Collections.Hashtable();
            ViewModel["Action"] = "凭证审核";
            mode = ViewProvider.ExecuteQuery(ViewModel);
            var i = int.Parse(mode["State"].ToString());
            if (i == 0)
            {
                using (var query = new Fis.Win.Forms.BillQueryForm())
                {
                    var v = UIManager.ShowEdit<BillListForm>("BillListViewProvider", Agile.Engine.View.ViewState.Modify, ViewModel);
                    if (((DialogResult)v.ViewResult) == System.Windows.Forms.DialogResult.Yes)
                    {
                        ViewModel["Action"] = "凭证审核提交";
                        if (ViewProvider.ExecuteUpdate(ViewModel))
                        {
                            XtraMessageBox.Show("凭证审核成功！");
                            //ViewProvider.InitializeViewModel(ViewModel);
                            Close();
                        }
                        else
                        {
                            XtraMessageBox.Show("凭证审核失败,请稍候重试！");
                        }
                        return;
                    }
                }
            }
            else if (i < 0)
            {
                XtraMessageBox.Show("凭证尚未提交，请先上传");
                System.Collections.Hashtable args = new System.Collections.Hashtable();
                args["filter0"] = string.Format(" AND DATEPART(month, FENTERDATE) = {0} AND FSYNC < 1", AppSession.Range);
                args["filter1"] = "";
                UIManager.ShowList<Forms.BillListForm>("BillListViewProvider", args);
            }
            else
            {
                XtraMessageBox.Show(string.Format("错误初始凭证数：{0},请修改后，再进行审核！", mode["ErrorBillMasterCount"]));
                System.Collections.Hashtable args = new System.Collections.Hashtable();
                args["filter0"] = string.Format("and m.SID in ('{0}') ", mode["ErrorBillMasterID"].ToString());
                args["filter1"] = "";
                UIManager.ShowList<Forms.BillListForm>("BillListViewProvider", args);
            }
            return;
        }

        private void ReverseCertificateAudit()
        {
            var BillMasterTB = ViewModel["BillMasterTB"] as DataTable;
            if (int.Parse(BillMasterTB.Compute("count(SID)", string.Format("FSTATUS=1 and FCHECKED='{0}'", ViewModel["FCHECKED"])).ToString()) == 0)
            {
                XtraMessageBox.Show("没有需要反审核的凭证！");
                return;
            }
            System.Collections.Hashtable mode = new System.Collections.Hashtable();
            ViewModel["Action"] = "凭证反审核";
            using (var query = new Fis.Win.Forms.BillQueryForm())
            {
                var v = UIManager.ShowEdit<BillListForm>("BillListViewProvider", Agile.Engine.View.ViewState.Modify, ViewModel);
                if (((DialogResult)v.ViewResult) == System.Windows.Forms.DialogResult.Yes)
                {
                    ViewModel["Action"] = "凭证反审核提交";
                    if (ViewProvider.ExecuteUpdate(ViewModel))
                    {
                        XtraMessageBox.Show("凭证反审核成功！");
                        //ViewProvider.InitializeViewModel(ViewModel);
                        Close();
                    }
                    else
                    {
                        XtraMessageBox.Show("凭证审核失败,请稍候重试！");
                    }
                    return;
                }
            }
            return;
        }

        #endregion

        #region //凭证过账

        private void CertificatePosting()
        {
            System.Collections.Hashtable mode = new System.Collections.Hashtable();
            ViewModel["Action"] = "凭证过账";
            mode = ViewProvider.ExecuteQuery(ViewModel);
            if (mode["State"].Equals(-1))
            {
                ShowUnSyncForm();
                return;
            }
            XtraMessageBox.Show(mode["Message"].ToString());
            if (mode["State"].Equals(0))
            {
                Close();
            }
            return;
        }

        private void ReverseCertificatePosting()
        {
            System.Collections.Hashtable mode = new System.Collections.Hashtable();
            ViewModel["Action"] = "凭证反过账";
            mode = ViewProvider.ExecuteQuery(ViewModel);
            XtraMessageBox.Show(mode["Message"].ToString());
            if (mode["State"].Equals(0))
            {
                Close();
            }
            return;
        }

        #endregion

        #region //结账

        public void AccountSettle()
        {
            var Year = int.Parse(ViewModel["Year"].ToString());
            var Range = int.Parse(ViewModel["Range"].ToString());
            var NowTime = System.DateTime.Now;
            if (Year > NowTime.Year)
            {
                XtraMessageBox.Show("由于本日在当前会计期间起始日期之前，所以无法进行结账！");
                return;
            }
            if (Year == NowTime.Year)
            {
                if (Range > NowTime.Month)
                {
                    XtraMessageBox.Show("由于本日在当前会计期间起始日期之前，所以无法进行结账！");
                    return;
                }
                if (Range == NowTime.Month)
                {
                    if (NowTime.Day < DateTime.DaysInMonth(Year, Range))
                    {
                        if (XtraMessageBox.Show(NowTime.Day + "日不是当前会计期间的最后一天，\r\n结账后将无法输入当前会计期间内的凭证。\r\n确定要执行结账吗？", "", MessageBoxButtons.YesNo) !=
                         System.Windows.Forms.DialogResult.Yes)
                        {
                            return;
                        }
                    }
                }
            }
            if (XtraMessageBox.Show(string.Format("是否进行{0}年{1}期结账？", Year, Range), "", MessageBoxButtons.YesNo) !=
              System.Windows.Forms.DialogResult.Yes)
            {
                return;
            }
            System.Collections.Hashtable mode = new System.Collections.Hashtable();
            ViewModel["Action"] = "结账检测";
            mode = ViewProvider.ExecuteQuery(ViewModel);

            if (mode["State"].Equals(-1))
            {
                ShowUnSyncForm();
                return;
            }
            if (mode["State"].Equals(-2))
            {
                if (XtraMessageBox.Show(mode["Message"].ToString(), "", MessageBoxButtons.YesNo) ==
                          System.Windows.Forms.DialogResult.Yes)
                {
                    ViewModel["Action"] = "同步凭证号";
                    ViewProvider.ExecuteUpdate(ViewModel);
                    ViewProvider.InitializeViewModel(ViewModel);
                    AccountSettle();
                    return;
                }
            }
            if (mode["State"].Equals(1))
            {
                XtraMessageBox.Show(mode["Message"].ToString());
                return;
            }

            ViewModel["Action"] = "科目余额表生成";
            mode = ViewProvider.ExecuteQuery(ViewModel);
            if (mode["State"].Equals(1))
            {
                XtraMessageBox.Show(mode["Message"].ToString());
                return;
            }
            mode["Action"] = "结账信息提交";
            if (ViewProvider.ExecuteUpdate(mode))
            {
                XtraMessageBox.Show("结账成功！");
                //ViewProvider.InitializeViewModel(ViewModel);
                Close();
            }
            else
            {
                XtraMessageBox.Show("结账失败！");
            }
            return;
        }

        public void ReverseAccountSettle()
        {
            var Year = int.Parse(ViewModel["Year"].ToString());
            var Range = int.Parse(ViewModel["Range"].ToString());
            if (DateTime.Parse(string.Format("{0}-{1}-1 00:00:00", Year, Range)) <= DateTime.Parse(ViewModel["BookStarTime"].ToString()))
            {
                XtraMessageBox.Show("无法反结账到小于账套初始期间！");
                return;
            }
            if (XtraMessageBox.Show(string.Format("当前期间{0}年{1}期，是否进行反结账？", Year, Range), "", MessageBoxButtons.YesNo) !=
              System.Windows.Forms.DialogResult.Yes)
            {
                return;
            }
            ViewModel["Action"] = "反结账信息提交";
            if (ViewProvider.ExecuteUpdate(ViewModel))
            {
                XtraMessageBox.Show("反结账成功！");
                //ViewProvider.InitializeViewModel(ViewModel);
                Close();
            }
            else
            {
                XtraMessageBox.Show("反结账失败！");
            }
            return;
        }

        #endregion

        void ShowUnSyncForm()
        {
            XtraMessageBox.Show("凭证尚未提交，请先上传");
            System.Collections.Hashtable args = new System.Collections.Hashtable();
            args["filter0"] = string.Format(" AND DATEPART(month, FENTERDATE) = {0} AND FSYNC < 1", AppSession.Range);
            args["filter1"] = "";
            UIManager.ShowList<Forms.BillListForm>("BillListViewProvider", args);
        }


    }
}
